//
//  BTC+Account+BIP44.swift
//  XHWalletUtils
//
//  Created by xinph on 2020/5/19.
//  Copyright © 2020 xinph. All rights reserved.
//

import Foundation

extension BTC: BIP44 {
    public static func createWallet(_ path: String?, password: String, name: String = "BTC Wallet", mnemonics: String) -> coswift.Promise<Wallet> {
        let promise = coswift.Promise<XHWalletUtils.Wallet>()

        guard let path = path, path.isEmpty == false else {
            promise.reject(error: XHError(pathError))
            return promise
        }
        
        var meta = WalletMeta(chain: .btc, source: .mnemonic)
        //隔离认证
        meta.segWit = SegWit.p2wpkh
        let keystore: BTCMnemonicKeystore
        /// 依赖web3生成助记词
        do {
            keystore = try BTCMnemonicKeystore(password: password, mnemonic: mnemonics, path: path, metadata: meta)
            let name = name.isEmpty ? "Wallet BTC" : name
            let account = Account(name, address: keystore.address, coin: 0)
            let wallet = BTC(mnemonics, path: path, isHD: true, privateKey: keystore.xpri, publicKey: keystore.xpub)
            wallet.mnemonicKeystore = keystore
            Manager.IO.writeWallet(account, wallet: wallet)
            promise.fulfill(value: wallet)
        } catch {
            promise.reject(error: XHError(pathError))
            return promise
        }
        return promise
    }
    
    /////// 暂时先不做了...
    public func createNewAccount(_ password: String, name: String = "Account \((Manager.shared.wallets?[CoinBIP44.defaultBTCPath]?.accounts.count ?? 0)+1)", cache write: Bool = true, closure: @escaping (Result<Account>) -> Void) {
        guard self.isHDWallet, let keystore = self.mnemonicKeystore else { return closure(Result.failure(XHError(notSuppurt))) }
        closure(.failure(XHError(createAccountFailure)))
    }
    
    public func createSevralAccounts(_ password: String, need count: UInt64, cache write: Bool = false) {
        guard count > 0 else { return }
        var accounts: [Account] = []
        for _ in 0..<count {
            createNewAccount(password, cache: write) {
                if case Result.success(let act) = $0 {
                    accounts.append(act)
                }
            }
        }
    }
}
